<?php

class FacebookController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	// public $layout='//layouts/view';
    public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}


	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

 
	/**
	 * PLogin Facebook
	 * 
	 */
	public function actionLoginface()
	{
		ob_start();
		Yii::import('application.extensions.fbsdk.src.facebook',true);

		$facebook = new Facebook(array(
	            'appId' => '160758294084647',
	            'secret' => '3f6bb6d551374f335331a165828aea97',
	            'cookie' => true
	            ));

		$user = $facebook->getUser();
		echo var_dump($user);	
		if ($user) {
			  try {
			    // Proceed knowing you have a logged in user who's authenticated.
			  $user_profile = $facebook->api('/me');
			  } catch (FacebookApiException $e) {
			    //error_log($e);
			    $user = null;
			  }


		     if (!empty($user_profile )) {
		        # User info ok? Let's print it (Here we will be adding the login and registering routines)
		       	
		//========= Batch requests over the Facebook Graph API using the PHP-SDK ========
			// Save your method calls into an array
			$queries = array(
				array('method' => 'GET', 'relative_url' => '/'.$user),
				array('method' => 'GET', 'relative_url' => '/'.$user.'/home?limit=50'),
				array('method' => 'GET', 'relative_url' => '/'.$user.'/friends'),
				array('method' => 'GET', 'relative_url' => '/'.$user.'/photos?limit=6'),
				);
		
			// POST your queries to the batch endpoint on the graph.
			try{
				$batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST');
			}catch(Exception $o){
				//error_log($o);
			}
		
			//Return values are indexed in order of the original array, content is in ['body'] as a JSON
			//string. Decode for use as a PHP array.
			$user_info		= json_decode($batchResponse[0]['body'], TRUE);
			//$feed			= json_decode($batchResponse[1]['body'], TRUE);
			//$friends_list	= json_decode($batchResponse[2]['body'], TRUE);
			//$photos			= json_decode($batchResponse[3]['body'], TRUE);
		//========= Batch requests over the Facebook Graph API using the PHP-SDK ends =====
		

			$uid = $user_profile['id'];
			$email = $user_profile['email'];
			$user_birthday = $user_info['birthday'];
			$gender = $user_info['gender'];
		        $user = new UserSocial();
		        $userdata = $user->checkUser($uid, 'facebook', $email, $user_birthday,$gender ,$user_profile);
		        echo var_dump($userdata);
		        if(!empty($userdata)){

		           if ($userdata->password != NULL) {

		           	// login with account facebook
					$identity = new UserIdentity($userdata->username , $email);
					$identity->authenticate(true);	

			 		if($identity->errorCode === UserIdentity::ERROR_NONE) 
		            {
	                   Yii::app()->user->login($identity, NULL);
	                   $this->redirect(array('/site'));
		            } 
		            else  {
	                	$string ="<script type=\"text/javascript\">";
						$string .= "alert('Not login ! Please login try again'); document.location.replace('http://fansipang.com/index.php?r=user/login1232'); ";
						$string .= "</script>";
						echo $string;
		          }        
		         }else{
		         	$changepass = Yii::app()->createUrl('/user/facebook/newPassword',array('email'=>$email));
		              $this->redirect($changepass);
				}
		         }
			  }else {
			        # For testing purposes, if there was an error, let's kill the script
			$string ="<script type=\"text/javascript\">";
			$string .= "alert('Not login ! Please login try again'); document.location.replace('http://fansipang.com/index.php?r=user/login'); ";
			$string .= "</script>";
			echo $string;
			    }
		} else {
		    # There's no active session, let's generate one
		    $params = array(
			  'scope' =>'offline_access, publish_stream,read_stream,user_birthday, user_photos,email',
			  'redirect_uri' => 'http://fansipang.com/index.php?r=user/facebook/loginface'
			);
			$login_url = $facebook->getLoginUrl($params);
		    header("Location: " . $login_url);
		}
		ob_flush();
	}

	public function actionNewPassword()
	{
		ob_start();
		if (isset($_GET['email'])) {
			$email = $_GET['email'];
			$model = Users::model()->findByAttributes(array('email'=>$email));
			if ($model) {
				if(empty($model->password)) {
				  if (isset($_POST['Users'])) {
				  	$new = $_POST["newPassword"];
					$model->attributes=$_POST['Users'];
	            	$model->password = $_POST['Users']['password_repeat'];
	            		if ($model->password_repeat !== $new){
		                    $model->addError('password', 'Xác nhận Mật khẩu mới không đúng');
		                }else {
		                	if(!empty($model->password)){
							  $password_encrypt = Users::model()->encrypt($model->password_repeat);
							  $model->password = $password_encrypt;
							  if ($model->save(false))
			                    {
			                        // login 
			                        $identity = new UserIdentity($model->username,$new);
	                				$identity->authenticate();
	                				if($identity->errorCode == UserIdentity::ERROR_NONE) 
					                {
					                       Yii::app()->user->login($identity, NULL);
					                       $this->redirect(array('/site'));
					                } 
					                else  {
					                       $model->addError('password', 'Không thể đăng nhập được');   
					                }
			                    }
			                }else $model->addError('password', 'Mật khẩu không để trống !');
		                }
				}
				$profile = UserProfiles::model()->findByAttributes(array('user_id'=>$model->id));	
				$this->render('newPassword',array('model'=>$model,'profile'=>$profile));
				}else  $this->redirect(array('/Users/default/signin'));

			}else {
				$this->redirect(array('/Users/default/signup'));
			}
		}else{
			$this->redirect(array('/Users/default/signup'));
		}
		ob_flush();
	}
	


}